package com.jfinal.weixin.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.weixin.entity.Music;
import org.jsoup.Jsoup;

import java.net.URLEncoder;
import java.util.ArrayList;

public class Kuwoutil {


    public static ArrayList searchMusic(String searchName,int music_page){
        ArrayList list=new ArrayList();

        try {
            String search_url="http://www.kuwo.cn/api/www/search/searchMusicBykeyWord?key="+searchName+"&pn="+music_page+"&rn=20&httpsStatus=1&reqId=7531f720-ffac-11ed-8b7f-d7b55f0d1046";
            searchName= URLEncoder.encode(searchName,"UTF-8");
            String str= Jsoup.connect(search_url)
                .cookie("kw_token","aabbcc")
                .header("csrf","aabbcc")
                .referrer("http://www.kuwo.cn/")
                .ignoreContentType(true)
                .get().body().text();
            System.out.println(str);

            JSONObject jsonObject_1=JSONObject.parseObject(str).getJSONObject("data");
            int total=jsonObject_1.getInteger("total");

            JSONArray jsonArray=jsonObject_1.getJSONArray("list");
            for (int i=0;i<jsonArray.size();i++){
                JSONObject jsonMusic=jsonArray.getJSONObject(i);
                Music music=new Music();
                music.setMusic_name(jsonMusic.getString("name"));
                music.setRid(jsonMusic.getString("rid"));

                list.add(music);
            }

        }catch(Exception e)
        {
            e.printStackTrace();
        }
        return list;
    }

    public static String getMp3url(String rid)
    {
        String mp3playurl="";
        try {
            String play_url="http://www.kuwo.cn/api/v1/www/music/playUrl?mid="+rid+"&type=MP3&httpsStatus=1&reqId=2774cdb1-ff56-11ed-9399-430faafa9e0f";
            String str=Jsoup.connect(play_url).ignoreContentType(true).get().body().text();
            JSONObject jsonObject=JSONObject.parseObject(str);
            if (jsonObject.getInteger("code")!=-1)
            {
                mp3playurl=jsonObject.getJSONObject("data").getString("url");
            }
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return mp3playurl;
    }
}
